<?php

namespace Cframe\Caches\Types;
use \Memcache as Mem;
/**
 *
 *  保存内容保存到memcache
 *
 */
class Memcache {
    private $pconnect = false;
    private $mem = '';
    protected $types = [];
    public function __construct(){
        $this->mem = new Mem();
        $this->mem->connect('localhost',11211) or die ("Could not connect to memcache server");
    }

    /**
     * 增加数据到memcache
     * @param $key 键名
     * @param string $value
     */
    public function setValue($key, $value = ''){
        $value = $this->convertValue($value);
        if ($this->mem->get($key)){
            $this->mem->set($key,$value);
        }else{
            $this->mem->add($key,$value);
        }
    }

    /**
     * 从memcache获取数据
     * @param $key
     * @return array|string
     */
    public function getValue($key){
        return $this->mem->get($key);
    }

    /**
     * 添加类型到数组
     * @param array $type
     */
    public function setType(array $type = []){
        $this->types = array_merge($this->types,$type);
    }

    /**
     * 转换value类型
     * memcache类型只有 字符和数字 数组要转换
     * @param $value
     * @return array|string|void
     */
    public function convertValue($value){
        if (is_string($value) && is_numeric($value)){
            return $value;
        }
        if (is_array($value)){
            $value = serialize($value);
        }
        if (is_object($value)){
            $value = $this->object_to_array($value);
            $value = serialize($value);
        }
        return $value;
    }

    /**
     * 将对象类型转换成数组
     * @param $obj
     * @return array|void
     */
    public function object_to_array($obj) {
        $obj = (array)$obj;
        foreach ($obj as $k => $v) {
            if (gettype($v) == 'resource') {
                return;
            }
            if (gettype($v) == 'object' || gettype($v) == 'array') {
                $obj[$k] = (array)$this->object_to_array($v);
            }
        }

        return $obj;
    }

    /**
     * 转换key
     * @param $key
     * @return mixed
     */
    public function nameValue($key){
        return $key;
    }

    public function clearMem(){
        // 清空所有的数据
        $this->mem->flush();
    }

//    public function getMemcacheKeys() {
//        $list = array();
//        $allSlabs = $this->mem->getExtendedStats('slabs');
//        $items = $this->mem->getExtendedStats('items');
//        foreach($allSlabs as $server => $slabs) {
//            foreach($slabs AS $slabId => $slabMeta) {
//                $cdump = $this->mem->getExtendedStats('cachedump',(int)$slabId);
//                foreach($cdump AS $keys => $arrVal) {
//                    if (!is_array($arrVal)) continue;
//                    foreach($arrVal AS $k => $v) {
//                        $list[$k] = $v;
//                    }
//                }
//            }
//        }
//        return $list;
//    }

    public function __destruct() {

        // 关闭链接
        $this->mem->close();
    }
}